package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ThreadLocalUtil;
import com.zzyl.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Path;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 根据用户id查询对应的资源数据
     *
     * @return
     */
    @Override
    public List<MenuVo> getMyMenus() {
        Long userId = ThreadLocalUtil.get();
        //查询数据
        List<MenuVo> menuVoList = resourceMapper.selectMenuByUserId(userId);
        //构建 parentNo -> List<MenuVo> 的映射
        Map<String, List<MenuVo>> parentMap = menuVoList.stream().collect(Collectors.groupingBy(MenuVo::getParentResourceNo));

        //递归构建我的菜单信息
        buildTree(menuVoList, parentMap);
        return parentMap.get(SuperConstant.ROOT_RESOURCE_PARENT_ID);
    }

    /**
     * 多条件查询资源列表
     *
     * @param resourceDto
     * @return
     */
    @Override
    public List<ResourceVo> findResourceList(ResourceDto resourceDto) {
        List<Resource> resourceList = resourceMapper.selectList(resourceDto);
        return BeanUtil.copyToList(resourceList, ResourceVo.class);
    }

    /**
     * 资源树形
     *
     * @param resourceDto 查询条件
     */
    @Override
    public TreeVo resourceTreeVo(ResourceDto resourceDto) {

        //构建查询条件
        ResourceDto dto = ResourceDto.builder()
                .resourceType("m")
                .build();

        //查询所有资源数据
        List<Resource> resourceList = resourceMapper.selectList(dto);
        if (CollUtil.isEmpty(resourceList)) {
            throw new RuntimeException("资源信息未定义");
        }

        //提取构建根节点
        Resource rootResource = CollUtil.findOneByField(resourceList, "resourceNo", SuperConstant.ROOT_RESOURCE_PARENT_ID);

        //使用递归构建树形结构
        TreeItemVo vo = recursionTreeItem(rootResource, resourceList);

        //数据返回
        return TreeVo.builder().items(List.of(vo)).build();
    }

    @Override
    public void createResource(ResourceDto resourceDto) {
        //属性拷贝
        Resource resource = BeanUtil.toBean(resourceDto, Resource.class);

        //查询父资源
        Resource parentResource = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());

        //根据父资源编号创建当前资源的编号
        String resourceNo = createResourceNo(resource, parentResource);
        resource.setResourceNo(resourceNo);

        resourceMapper.insert(resource);
    }
    /**
     * 资源修改
     * @param dto
     * @return
     */
    @Override
    public void updateResource(ResourceDto dto) {
        Resource resource = BeanUtil.toBean(dto, Resource.class);
        resourceMapper.updateByPrimaryKeySelective(resource);
    }

    @Override
    public void enableOrDisable(ResourceDto dto) {
        Resource resource = resourceMapper.selectByResourceNo(dto.getParentResourceNo());
        if(resource.getDataState().equals("1")){
            if(dto.getDataState().equals("0")){
                throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
            }
        }

        String s = NoProcessing.processString(dto.getResourceNo());
        if(dto.getDataState().equals("1")){
            resourceMapper.updateByResourceNo(dto.getResourceNo(),dto.getDataState());
            resourceMapper.updateByParentResourceNo(s,"1");
        }

        resourceMapper.updateByResourceNo(dto.getResourceNo(),dto.getDataState());
    }

    /**
     * 删除菜单
     * @param menuId
     */
    @Override
    public void delete(String menuId) {
        Resource resource = resourceMapper.selectByResourceNo(menuId);
        if(resource.getDataState().equals("0")){
            throw new RuntimeException("该菜单为启用状态,不允许删除!");
        }
        int i = resourceMapper.hasChildByMenuId(menuId);
        if(i>0){
            throw new RuntimeException("该菜单下有子菜单,不可删除!");
        }

        resourceMapper.deleteByResourceNo(menuId);

    }

    /**
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     * 创建资源的编号（已提供）
     */
    private String createResourceNo(Resource resource, Resource parentResource) {
        //判断是否是按钮，如果是按钮，则不限制层级
        if (!StrUtil.equals(resource.getResourceType(),  "r")) {
            if (NoProcessing.processString(parentResource.getResourceNo()).length() / 3 >= 5) {
                //判断资源编号是否大于三级
                //100 001 000 000 000
                //100 001 001 000 000
                //100 001 001 001 000
                //100 001 001 001 001 001
                throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
            }
        }

        //根据父资源编号查询子资源
        ResourceDto dto = ResourceDto.builder().parentResourceNo(parentResource.getResourceNo()).build();
        List<Resource> resources = resourceMapper.selectList(dto);
        if (ObjectUtil.isEmpty(resources)) {
            //无下属节点，创建新的节点编号  100 001 001 001 000--->100 001 001 001 001
            return NoProcessing.createNo(parentResource.getResourceNo(), false);
        } else {
            //有下属节点，在已有的节点上追加，先获取已有节点的最大值--100001003000000
            Long maxNo = resources.stream().map(r -> Long.valueOf(r.getResourceNo())).max(Comparator.comparing(i -> i)).get();
            return NoProcessing.createNo(String.valueOf(maxNo), true);
        }
    }


    /**
     * 使用递归构建树形结构
     * 使用递归构建树形结构
     * 使用递归构建树形结构
     */
    private TreeItemVo recursionTreeItem(Resource rootResource, List<Resource> resourceList) {
        //构建每个资源的属性
        TreeItemVo treeItemVo = TreeItemVo.builder()
                .id(rootResource.getResourceNo())
                .label(rootResource.getResourceName())
                .build();

        //获取当前资源下子资源
        Collection<Resource> children = CollUtil.filterNew(resourceList, res -> StrUtil.equals(res.getParentResourceNo(), rootResource.getResourceNo()));

        //判断子资源是否为空
        if (ObjectUtil.isEmpty(children)) {
            return treeItemVo;
        }
        //构建子资源
        List<TreeItemVo> listChildren = children.stream().map(res -> recursionTreeItem(res, resourceList)).collect(Collectors.toList());

        treeItemVo.setChildren(listChildren);
        return treeItemVo;
    }


    /**
     * 递归构建我的菜单信息（已提供）
     */
    private void buildTree(List<MenuVo> menuVoList, Map<String, List<MenuVo>> parentMap) {
        menuVoList.forEach(menuVo -> {
            //补全数据
            menuVo.setMeta(MenuMetaVo.builder().title(menuVo.getName()).build());
            menuVo.setRedirect("/" + menuVo.getName());
            //根据当前资源编号查询子资源
            List<MenuVo> childrenList = parentMap.get(menuVo.getResourceNo());
            if (CollUtil.isNotEmpty(childrenList)) {
                buildTree(childrenList, parentMap);
                menuVo.setChildren(childrenList);
            }
        });
    }
}
